package dao;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import object.PageBean;
import object.TradeAddr;
import object.Transaction;
import object.UserCenter;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import pojo.Commodity;
import pojo.LogIncome;
import pojo.LogNoruserbill;
import pojo.TransactionDetails;
import pojo.TransactionLog;
import pojo.ZcArea;
import config.ConstantConfig;
import config.Sql2zcConfig;
import config.SqlConfig;

/**
 * 
 * @author zgy
 *
 */
@Repository
public class TransactionDao {
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	static Logger logger = Logger.getLogger(TransactionDao.class.getName());
	

	
	/**
	 * 获取商品列表
	 * @param curPage
	 * @param pageSize
	 * @return
	 */
	public ArrayList<Commodity> queryCommodityList(Integer curPage,Integer pageSize){
		final ArrayList<Commodity> commodities = new ArrayList<>();
		Object[] params = new Object[]{(curPage-1)*pageSize,curPage*pageSize};
		jdbcTemplate.query(SqlConfig.queryCommodities, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				Commodity commodity = new Commodity();
				commodity.setId(rs.getInt("transaction_commodity_id"));
				commodity.setName(rs.getString("transaction_commodity_name"));
				commodity.setPicture(rs.getBytes("transaction_commodity_picture"));
				commodity.setDescription(rs.getString("transaction_commodity_description"));
				commodity.setPrice(rs.getBigDecimal("transaction_commodity_price"));
				commodities.add(commodity);
			}
		});
		return commodities;
	}
	
	/**
	 * 获取交易地址列表
	 * @param curPage
	 * @param pageSize
	 * @return
	 */
	public ArrayList<TradeAddr> queryTradeAddrList(String platformId){
		final ArrayList<TradeAddr> tradeAddrs = new ArrayList<>();
		Object[] params = new Object[]{platformId};
		jdbcTemplate.query(SqlConfig.queryTradeAddr, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				TradeAddr tradeAddr = new TradeAddr();
				/*tradeAddr.setId(rs.getInt("transaction_address_id"));
				tradeAddr.setProvince(rs.getString("transaction_address_province"));
				tradeAddr.setCity(rs.getString("transaction_address_city"));
				tradeAddr.setArea(rs.getString("transaction_address_area"));
				tradeAddr.setStreet(rs.getString("transaction_address_street"));
				tradeAddr.setAddr(rs.getString("transaction_address_addr"));
				tradeAddr.setName(rs.getString("transaction_address_name"));
				tradeAddr.setMobileNum(rs.getString("transaction_address_mobileNum"));
				tradeAddr.setStatus(rs.getString("transaction_address_status"));*/
				tradeAddr.setId(rs.getInt("user_address_id"));
				tradeAddr.setProvince(rs.getString("user_address_province"));
				tradeAddr.setCity(rs.getString("user_address_city"));
				tradeAddr.setArea(rs.getString("user_address_area"));
				tradeAddr.setStreet(rs.getString("user_address_street"));
				tradeAddr.setAddr(rs.getString("user_address_addr"));
				tradeAddr.setName(rs.getString("user_address_name"));
				tradeAddr.setMobileNum(rs.getString("user_address_mobileNum"));
				tradeAddr.setStatus(rs.getString("user_address_status"));
				tradeAddrs.add(tradeAddr);
			}
		});
		return tradeAddrs;
	}
	
	/**
	 * 查询交易订单
	 * @param orderNum
	 * @return
	 */
	public Transaction queryTransaction(String orderNum){
		final Transaction transaction = new Transaction();
		Object[] params = new Object[]{orderNum};
		jdbcTemplate.query(SqlConfig.queryTransaction, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				transaction.setOrderNum(rs.getString("transaction_orderNum"));
				transaction.setStartTime(rs.getTimestamp("transaction_startTime"));
				transaction.setEndTime(rs.getTimestamp("transaction_endTime"));
				transaction.setStatus(rs.getString("transaction_status"));
				transaction.setSendAndReceiveType(rs.getString("transaction_sendAndReceiveType"));
				transaction.setTotalNum(rs.getInt("transaction_totalNums"));
				transaction.setPayment(rs.getString("transaction_payment"));
				transaction.setUserID(rs.getInt("transaction_userID"));
				transaction.setPaymentPrice(rs.getBigDecimal("transaction_paymentPrice"));
				transaction.setComment(rs.getString("transaction_comment"));
			}
		});
		return transaction;
	}
	
	/**
	 * 查询交易订单
	 * @param platformId
	 * @return
	 */
	public ArrayList<Transaction> queryTransactionList(String platformId){
		final ArrayList<Transaction> transactions = new ArrayList<>();
		Object[] params = new Object[]{platformId};
		jdbcTemplate.query(SqlConfig.queryTransactionList, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				Transaction transaction = new Transaction();
				transaction.setOrderNum(rs.getString("transaction_orderNum"));
				transaction.setStartTime(rs.getTimestamp("transaction_startTime"));
				transaction.setEndTime(rs.getTimestamp("transaction_endTime"));
				transaction.setStatus(rs.getString("transaction_status"));
				transaction.setSendAndReceiveType(rs.getString("transaction_sendAndReceiveType"));
				transaction.setTotalNum(rs.getInt("transaction_totalNums"));
				transaction.setPaymentPrice(rs.getBigDecimal("transaction_paymentPrice"));
				transaction.setPayment(rs.getString("transaction_payment"));
				transaction.setCheck(rs.getString("transaction_check"));
				transaction.setComment(rs.getString("transaction_comment"));
				transactions.add(transaction);
			}
		});
		return transactions;
	}
	
	/**
	 * 订单明细查询
	 * @param orderNum
	 * @return
	 */
	public ArrayList<TransactionDetails> queryTransactionDetailList(String orderNum){
		final ArrayList<TransactionDetails> transactionDetails = new ArrayList<>();
		Object[] params = new Object[]{orderNum};
		jdbcTemplate.query(SqlConfig.queryTransactionDetails, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				TransactionDetails transactionDetail = new TransactionDetails();
				transactionDetail.setGoodsName(rs.getString("transaction_details_goodsName"));
				transactionDetail.setGoodsPrice(rs.getBigDecimal("transaction_details_goodsPrice"));
				transactionDetail.setDescription(rs.getString("transaction_details_description"));
				transactionDetail.setGoodsNum(rs.getInt("transaction_details_goodsNum"));
				transactionDetails.add(transactionDetail);
			}
		});
		return transactionDetails;
	}
	
	/**
	 * 交易流程查询
	 * @param orderNum
	 * @return
	 */
	public ArrayList<TransactionLog> queryTransactionLogList(String orderNum){
		final ArrayList<TransactionLog> transactionLogs = new ArrayList<>();
		Object[] params = new Object[]{orderNum};
		jdbcTemplate.query(SqlConfig.queryTransactionLogs, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				TransactionLog transactionLog = new TransactionLog();
				transactionLog.setUserID(rs.getInt("transaction_log_userID"));
				transactionLog.setTime(rs.getTimestamp("transaction_log_time"));
				transactionLog.setDescription(rs.getString("transaction_log_description"));
				transactionLogs.add(transactionLog);
			}
		});
		return transactionLogs;
	}
	
	/**
	 * 查询已完成订单列表
	 * @param platformId
	 * @return
	 */
	public ArrayList<Transaction> queryCompleteTrade(String platformId){
		final ArrayList<Transaction> transactions = new ArrayList<>();
		Object[] params = new Object[]{platformId};
		jdbcTemplate.query(SqlConfig.queryCompleteTrade, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				Transaction transaction = new Transaction();
				transaction.setOrderNum(rs.getString("transaction_orderNum"));
				transaction.setStartTime(rs.getTimestamp("transaction_startTime"));
				transaction.setEndTime(rs.getTimestamp("transaction_endTime"));
				transaction.setStatus(rs.getString("transaction_status"));
				transaction.setSendAndReceiveType(rs.getString("transaction_sendAndReceiveType"));
				transaction.setTotalNum(rs.getInt("transaction_totalNums"));
				transaction.setPaymentPrice(rs.getBigDecimal("transaction_paymentPrice"));
				transaction.setPayment(rs.getString("transaction_payment"));
				transaction.setComment(rs.getString("transaction_comment"));
				transactions.add(transaction);
			}
		});
		return transactions;
	}
	
	/**
	 * 个人中心
	 * @param platformId
	 * @return
	 */
	public UserCenter queryUserCenter(String platformId){
		final UserCenter userCenter = new UserCenter();
		Object[] params = new Object[]{platformId};
		jdbcTemplate.query(SqlConfig.wxUserCenter, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				userCenter.setUserId(rs.getInt("user_id"));
				userCenter.setFirstName(rs.getString("user_firstName"));
				userCenter.setLastName(rs.getString("user_lastName"));
				userCenter.setMobileNum(rs.getString("user_mobileNum"));
				userCenter.setIcon(rs.getBytes("user_icon"));
				userCenter.setBalance(rs.getBigDecimal("user_balance"));
			}
		});
		return userCenter;
	}
	
	/**
	 * 新增交易订单
	 * @param transaction
	 * @return
	 */
	public boolean insertTransaction(pojo.Transaction transaction) {
		Object[] params = new Object[]{
				transaction.getOrderNum(),transaction.getUserID(),transaction.getReceiveAddr(),
				transaction.getStatus(),transaction.getSendAndReceiveType(),transaction.getReceiveOrderTimeStart(),
				transaction.getSendOrderTimeEnd(),transaction.getSendOrderTimeStart(),transaction.getReceiveOrderTimeEnd(),
				transaction.getStartTime(),transaction.getPayment(),transaction.getCheck(),
				transaction.getPaymentPrice(),transaction.getTotalNums(),transaction.getComment()
				};
		if(jdbcTemplate.update(SqlConfig.insertTransaction, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 更新交易订单
	 * @param transaction
	 * @return
	 */
	public boolean updateTransaction(pojo.Transaction transaction) {
		Object[] params = new Object[]{
				transaction.getPaymentPrice(),transaction.getTotalNums(),transaction.getOrderNum()
		};
		if(jdbcTemplate.update(SqlConfig.updateTransaction, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 新增订单明细
	 * @param transactionDetails
	 * @return
	 */
	public boolean insertTransactionDetails(pojo.TransactionDetails transactionDetails) {
		Object[] params = new Object[]{
				transactionDetails.getGoodsName(),transactionDetails.getGoodsPrice(),transactionDetails.getDescription(),
				transactionDetails.getGoodsNum(),transactionDetails.getOrderNum()
		};
		if(jdbcTemplate.update(SqlConfig.insertTransactionDetail, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 删除订单明细
	 * @param orderNum
	 * @return
	 */
	public boolean deleteTransactionDetails(String orderNum) {
		Object[] params = new Object[]{orderNum};
		if(jdbcTemplate.update(SqlConfig.deleteTransactionDetail, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 新增交易日志
	 * @param transactionLog
	 * @return
	 */
	public boolean insertTransactionLog(pojo.TransactionLog transactionLog) {
		Object[] params = new Object[]{
				transactionLog.getUserID(),transactionLog.getTime(),transactionLog.getDescription(),transactionLog.getOrderNum()
		};
		if(jdbcTemplate.update(SqlConfig.insertTransactionLog, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 根据ID查询商品信息
	 * @param commodityId
	 * @return
	 */
	public Commodity queryCommodityById(int commodityId){
		final Commodity commodity = new Commodity();
		Object[] params = new Object[]{commodityId};
		jdbcTemplate.query(SqlConfig.queryCommodityById, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				commodity.setId(rs.getInt("transaction_commodity_id"));
				commodity.setName(rs.getString("transaction_commodity_name"));
				commodity.setPicture(rs.getBytes("transaction_commodity_picture"));
				commodity.setDescription(rs.getString("transaction_commodity_description"));
				commodity.setPrice(rs.getBigDecimal("transaction_commodity_price"));
				commodity.setCreatTime(rs.getTimestamp("transaction_commodity_creatTime"));
			}
		});
		return commodity;
	}
	
	/**
	 * 新增交易地址
	 * @param transactionAddr
	 * @return
	 */
	public boolean insertTradeAddr(pojo.TransactionAddr transactionAddr) {
		Object[] params = new Object[]{transactionAddr.getUserID(),transactionAddr.getAddrType(),transactionAddr.getProvince(),
				transactionAddr.getCity(),transactionAddr.getArea(),transactionAddr.getStreet(),
				transactionAddr.getAddr(),transactionAddr.getName(),transactionAddr.getMobileNum(),transactionAddr.getStatus()
				};
		if(jdbcTemplate.update(SqlConfig.insertTradeAddr, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 重置所有正常地址
	 */
	public boolean clearAddrStatus(Integer userID) {
		Object[] params = new Object[]{"0",userID};
		if(jdbcTemplate.update(SqlConfig.clearAddrStatus, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 更新交易地址
	 * @param transactionAddr
	 * @return
	 */
	public boolean updateTradeAddr(pojo.TransactionAddr transactionAddr) {
		Object[] params = new Object[]{transactionAddr.getProvince(),transactionAddr.getCity(),transactionAddr.getArea(),transactionAddr.getStreet(),
				transactionAddr.getAddr(),transactionAddr.getName(),transactionAddr.getMobileNum(),transactionAddr.getStatus(),transactionAddr.getAddrId()
		};
		if(jdbcTemplate.update(SqlConfig.updateTradeAddr, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 删除交易地址
	 * @param transactionAddr
	 * @return
	 */
	public boolean deleteTradeAddr(pojo.TransactionAddr transactionAddr) {
		Object[] params = new Object[]{ConstantConfig.TRANSACTION_ADDRESS_STATUS_DELETE,transactionAddr.getAddrId()};
		if(jdbcTemplate.update(SqlConfig.deleteTradeAddr, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 取消交易订单
	 * @param transaction
	 * @return
	 */
	public boolean cancelTransaction(pojo.Transaction transaction) {
		Object[] params = new Object[]{ConstantConfig.TRANSACTION_STATUS_CANCEL,transaction.getOrderNum()};
		if(jdbcTemplate.update(SqlConfig.deleteTransaction, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 交易订单支付
	 * @param orderNum
	 * @return
	 */
	public boolean payTransaction(String orderNum) {
		Object[] params = new Object[]{ConstantConfig.TRANSACTION_PAYED,orderNum};
		if(jdbcTemplate.update(SqlConfig.updateTransactionPay, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 查询充值状态
	 * @param orderNum
	 * @return
	 */
	public String queryLogIncomeStatus(String orderNum){
		Object[] params = new Object[]{orderNum};
		String status=jdbcTemplate.queryForObject(SqlConfig.queryLogncomeStatus, params, String.class);
		return status;
	}
	
	/**
	 * 查询交易订单支付
	 * @param orderNum
	 * @return
	 */
	public String queryTransactionPayStatus(String orderNum){
		Object[] params = new Object[]{orderNum};
		String status=jdbcTemplate.queryForObject(SqlConfig.queryTransactionPayStatus, params, String.class);
		return status;
	}
	
	/**
	 * 查询账户余额
	 * @param orderNum
	 * @return
	 */
	public BigDecimal queryUserBalance(String openId){
		Object[] params = new Object[]{openId};
		BigDecimal balance=jdbcTemplate.queryForObject(SqlConfig.queryUserBalance, params, BigDecimal.class);
		return balance;
	}
	
	/**
	 * 查询用户扣费表的个数
	 * @param orderNum
	 * @return
	 */
	public Integer queryNorUserBillCount(String orderNum){
		Object[] params = new Object[]{orderNum};
		Integer count=jdbcTemplate.queryForObject(SqlConfig.queryLogNorUserBillCount, params, Integer.class);
		return count;
	}
	
	/**
	 * 插入用户扣费记录
	 * @param orderNum
	 * @return
	 */
	public boolean insertNorUserBill(LogNoruserbill noruserbill ){
		Object[] params = new Object[]{noruserbill.getLogNorUserBillUserID(),noruserbill.getLogNorUserBillUpdateTime(),noruserbill.getLogNorUserBillMoney(),
				noruserbill.getLogNorUserBillBalance(),noruserbill.getLogNorUserBillContentType(),noruserbill.getLogNorUserBillContent(),noruserbill.getLogNorUserBillPayment(),
				noruserbill.getLogNorUserBillPayMobile(),noruserbill.getLogNorUserBillInSeq(),noruserbill.getLogNorUserBillType(),noruserbill.getLogNorUserStatus()};
		if(jdbcTemplate.update(SqlConfig.insertNorUserBill, params) != 0)
			return true;
		return false;
	}
	
	/**
	 *插入入账表记录
	 * @param orderNum
	 * @return
	 */
	public boolean insertLogIncome(LogIncome income){
		Object[] params = new Object[]{income.getLogIncomeTypeId(),income.getLogIncomeOrgId(),income.getLogIncomeOrgName(),
				income.getLogIncomeAgentId(),income.getLogIncomeUserId(),income.getLogIncomeCreateTime(),income.getLogIncomeMoney(),
				income.getLogIncomeFeedbackMoney(),income.getLogIncomeChannel(),income.getLogIncomeInSeq(),income.getLogIncomeStatus()};
		if(jdbcTemplate.update(SqlConfig.insertLogIncome, params) != 0)
			return true;
		return false;
	}
	
	
	/**
	 * 更新用户扣费表状态
	 * @param orderNum
	 * @return
	 */
	public boolean updateNorUserBillStatus(String orderNum,String wxOrderNum,BigDecimal money ){
		Object[] params = new Object[]{wxOrderNum,money,orderNum};
		if(jdbcTemplate.update(SqlConfig.updateNorUserBillStatus, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 更新入账表状态
	 * @param orderNum
	 * @return
	 */
	public boolean updateLogIncomeStatus(String orderNum,String wxOrderNum,BigDecimal money ){
		Object[] params = new Object[]{wxOrderNum,money,orderNum};
		if(jdbcTemplate.update(SqlConfig.updateLogIncomeStatus, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 更新账户余额
	 * @param orderNum
	 * @return
	 */
	public boolean updateUserBalance(BigDecimal money,String orderNum){
		Object[] params = new Object[]{money,orderNum};
		if(jdbcTemplate.update(SqlConfig.updateUserBalance, params) != 0)
			return true;
		return false;
	}
	
	/**
	 * 查询用户扣费列表---后面动态分页加载
	 * @param userId
	 * @return
	 */
	public List<LogNoruserbill> queryUserBillList(Integer userId){
		final List<LogNoruserbill> userBillList = new ArrayList<>();
		Object[] params = new Object[]{userId};
		jdbcTemplate.query(SqlConfig.queryLogNorUserBill, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				LogNoruserbill userbill = new LogNoruserbill();
				userbill.setLogNorUserBillBalance(rs.getBigDecimal("log_norUserBill_balance"));
				userbill.setLogNorUserBillMoney(rs.getBigDecimal("log_norUserBill_money"));
				userbill.setLogNorUserBillInSeq(rs.getString("log_norUserBill_inSeq"));
				userbill.setLogNorUserBillUpdateTime(rs.getTimestamp("log_norUserBill_updateTime"));
				userBillList.add(userbill);
			}
		});
		return userBillList;
	}
	
	/**
	 * 查询用户充值列表---后面动态分页加载
	 * @param userId
	 * @return
	 */
	public List<LogIncome> queryIncomeList(Integer userId){
		final List<LogIncome> incomeList = new ArrayList<>();
		Object[] params = new Object[]{userId};
		jdbcTemplate.query(SqlConfig.queryLogincome, params,new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				LogIncome income = new LogIncome();
				income.setLogIncomeBalance(rs.getBigDecimal("log_income_balance"));
				income.setLogIncomeMoney(rs.getBigDecimal("log_income_money"));
				income.setLogIncomeChannel(rs.getInt("log_income_channel"));
				income.setLogIncomeCreateTime(rs.getTimestamp("log_income_createTime"));
				incomeList.add(income);
			}
		});
		return incomeList;
	}
}